package com.springboot.study.tests.annotation;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Objects;

/**
 * @Author: guodong
 * @Date: 2021/7/24 13:07
 * @Version: 1.0
 * @Description:
 */
public class EnumStringValidator2 implements ConstraintValidator<EnumValidateAnnotation2, String> {

    private String methodStr;

    private Class<? extends Enum> enumClass;

    @Override
    public void initialize(EnumValidateAnnotation2 constraintAnnotation) {
        methodStr = constraintAnnotation.method();
        enumClass = constraintAnnotation.enumClass();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (value == null) {
            return false;
        }
        try {
            // 反射获取校验需要调用的枚举的方法
            Method method = enumClass.getMethod(methodStr);
            boolean result = false;
            // 获取所有的枚举值
            Enum[] enums = enumClass.getEnumConstants();
            // 对每一个枚举值调用 校验的方法，获取返回值，和入参作比较
            for (Enum e : enums) {
                Object returnValue = method.invoke(e);
                result = Objects.equals(returnValue, value);
            }
            return result;
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            // 异常处理
        } catch (Throwable throwable) {
            // 异常处理
        }
        return false;
    }

}

